package com.rc.saas.tenant.controller.msg;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.ImportExcelUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.msg.TenantNotice;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.msg.TenantNoticeSearch;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.msg.TenantNoticeService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author frog
 * @date 2019/12/17
 */
@Controller
@RequestMapping("/tenantNotice")
public class TenantNoticeController {
    private static Logger logger = LogManager.getLogger(TenantNoticeController.class);

    @Autowired
    private TenantNoticeService tenantNoticeService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private UploadComponent uploadComponent;

    /**
     * 跳转公告或通知页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String tenantNoticePage() {
        return "/templates/msg/tenantNotice";
    }

    /**
     * 返回公告或通知列表数据
     *
     * @return
     */
//    @RequestBodyDecrypt   //请求数据解密
//    @ResponseBodyEncrypt  //响应数据加密
    @ResponseBody
    @RequestMapping(value = "/listPageTenantNotice", method = RequestMethod.POST)
    public WebPageInfo pageTenantNotice(@RequestBody TenantNoticeSearch baseSearch) {
        PageInfo<TenantNotice> pageInfo = tenantNoticeService.pageTenantNotice(baseSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转公告或通知页面
     *
     * @return
     */
    @RequestMapping(value = "/addTenantNotice", method = RequestMethod.GET)
    public String addTenantNotice() {
        return "/templates/msg/addTenantNotice";
    }

    /**
     * 跳转编辑公告或通知页面
     *
     * @return
     */
    @RequestMapping(value = "/editTenantNotice/{customMsgId}", method = RequestMethod.GET)
    public String editTenantNotice(@PathVariable("customMsgId") Long customMsgId, Model model) {
        TenantNotice tenantNotice = tenantNoticeService.selectByPrimaryKey(customMsgId);
        model.addAttribute("tenantNotice", tenantNotice);
        return "/templates/msg/editTenantNotice";
    }

    /**
     * 保存公告或通知
     *
     * @return
     */
    @RequestMapping(value = "/saveTenantNotice", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveTenantNotice(TenantNotice tenantNotice, @RequestParam(value = "file", required = false) MultipartFile file) {
        if (!BeanUtil.isValid(tenantNotice.getTitle())) {
            return TResponse.FAIL("请输入正确的参数");
        }
        TenantUser user = ShiroUtils.getSessionUser();

        try {
//            if ("1".equals(tenantNotice.getNoticeType())) {
//                if (file.getSize() != 0) {
//                    TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file);
//                    if (tResponse.getStatus() == 200) {
//                        tenantNotice.setImgUrl((String) tResponse.getData());
//                    } else {
//                        return tResponse;
//                    }
//                } else {
//                    return TResponse.FAIL("请上传图片");
//                }
//            }

            if (tenantNotice.getNoticeId() == null) {
                tenantNotice.setStatus("1");
                tenantNotice.setTenantCode(user.getTenantCode());
                tenantNoticeService.insertSelective(tenantNotice);

            } else {
                tenantNoticeService.updateByPrimaryKeySelective(tenantNotice);
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存保存公告或通知", e);
            return TResponse.FAIL("操作失败");
        }
    }

    private String updateMobileFormat(TenantNotice tenantNotice, TenantUser user) {
        String tenantCode = user.getTenantCode();
        tenantCode = tenantCode + "|";

        StringBuilder mobilesSB = new StringBuilder();
        String[] mobiles = tenantNotice.getMobiles().split(",");
        for (String mobile : mobiles) {
            mobilesSB.append(tenantCode + mobile);
        }
        return mobilesSB.toString();
    }


    /**
     * 删除公告或通知
     *
     * @return
     */
    @RequestMapping(value = "/deleteTenantNotice", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteTenantNotice(Long tenantNoticeId) {
        try {
            tenantNoticeService.deleteByPrimaryKey(tenantNoticeId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 修改公告状态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/udpateNoticeStatus", method = RequestMethod.POST)
    public TResponse udpateNoticeStatus(Long id, String status) {
        TenantNotice tenantNotice = tenantNoticeService.selectByPrimaryKey(id);
        tenantNotice.setStatus(status);
        tenantNoticeService.updateByPrimaryKey(tenantNotice);
        return TResponse.SUCCESS();
    }


    /**
     * 上传用户excel
     *
     * @return
     */
    @RequestMapping(value = "/uploadMemberMobile", method = RequestMethod.POST)
    @ResponseBody
    public TResponse uploadMemberMobile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        try {
            String filename = file.getOriginalFilename();
            String fileLastName = filename.substring(filename.length() - 3, filename.length());
            if (!"xls".equals(fileLastName) && !"lsx".equals(fileLastName)) {
                return TResponse.FAIL("请上传xls或者xlsx格式的文件");
            }

            Map<String, Object> result = new HashMap<String, Object>();
            List<String> mobiles = new ArrayList<String>();

            //excel文件上传
            String path = request.getSession().getServletContext().getRealPath("/");
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            try {
                if (!file.isEmpty()) {
                    // 这里将上传得到的文件保存指定目录下
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, fileName));
                }

                InputStream in = null;
                List<List<Object>> listob = null;
                in = file.getInputStream();
                listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
                for (int i = 0; i < listob.size(); i++) {
                    List<Object> lo = listob.get(i);
                    //TODO 根据excel格式获取指定的参数,还可优化:用正则表达式匹配过滤不符合的参数
                    String mobile = String.valueOf(lo.get(0));
                    mobiles.add(mobile);
                }

            } catch (Exception e) {
                //TODO 记录完善的日志和异常处理
                logger.error("batchAddMobiles()失败,原因为:" + e.getMessage(), e);
            } finally {
                //处理完后需删除本地文件
                File file2 = new File(path + File.separator + fileName);
                if (file2.exists()) {
                    file2.delete();
                }
            }
            TenantUser user = ShiroUtils.getSessionUser();
            LinkedList<String> linkedList = new LinkedList<>();
            String sign = ",";
            int failMobile = 0;
            //添加判断&业务处理
            if (null != mobiles && mobiles.size() > 0) {
                //TODO 业务逻辑处理
                for (String mobile : mobiles) {
                    MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
                    if (memberInfo != null) {
                        linkedList.add(mobile + sign);
                    } else {
                        failMobile++;
                    }
                }
            }
            return TResponse.SUCCESS_DATA_MESSAGE(linkedList, String.format("已成功导入%d条手机号码,为你删除无效号码%d条", linkedList.size(), failMobile));
        } catch (Exception e) {
            logger.error("上传用户excel失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Object uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file != null && file.getSize() != 0 && file.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file);

            Map<String, Object> result = new HashMap<>();
            Map<String, String> fileStore = new HashMap<>();
            fileStore.put("url", imgUrl);
            result.put("errno", 0);
            result.put("data", fileStore);


            return result;

        }
        return TResponse.SUCCESS();
    }

    /**
     * 导出内容设置列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(TenantNoticeSearch tenantNoticeSearch, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(tenantNoticeSearch);
            PageInfo<TenantNotice> page = tenantNoticeService.pageTenantNotice(tenantNoticeSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("通知公告列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TenantNotice.class).sheet("通知公告列表").doWrite(page.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出通知公告列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }
}
